package com.sam.example3.client;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

public class MinaClient01 {
	private static Logger logger = Logger.getLogger(MinaClient01.class);

	private static String HOST = "127.0.0.1";

	private static int PORT = 3005;
	
	public static void main(String[] args) {
		
		IoConnector connector = new NioSocketConnector();
		connector.setConnectTimeoutMillis(60000);
		
		connector.getFilterChain().addLast(   //添加消息过滤器
				"codec",
				new ProtocolCodecFilter(new TextLineCodecFactory(
						Charset.forName("UTF-8"), 
						LineDelimiter.WINDOWS.getValue(),
						LineDelimiter.WINDOWS.getValue())));
		
		connector.setHandler(new Demo1ClientHandler());

		IoSession session = null;
		
		try{
			ConnectFuture future = connector.connect(new InetSocketAddress(HOST , PORT));
			// 等待连接创建完成
			future.awaitUninterruptibly();
			session = future.getSession();
			session.write("Mina client connect success!!!");
		} catch (Exception e){
			e.printStackTrace();
			logger.error("客户端链接异常...", e);
		}
		
		//等待连接关闭
		session.getCloseFuture().awaitUninterruptibly();
		connector.dispose();
	}

}
